package com.itboye.ihomebank.choosecity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.choosecity.MyLetterListView.OnTouchingLetterChangedListener;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.FlowLayout;
import com.itboye.ihomebank.db.CityNoDBManager;
import com.itboye.ihomebank.db.DBManager;
import com.itboye.ihomebank.util.SPUtils;

/**
 * 城市列表
 * 
 * @author sy
 * 
 */
public class CityListActivity extends BaseOtherActivity implements OnClickListener {
	private BaseAdapter adapter;
	private ListView city_list;
	private TextView overlay;
	private MyLetterListView cityLetterListView;
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private Handler handler;
	private OverlayThread overlayThread;
	private SQLiteDatabase database;
	private ArrayList<CityModel> mCityNames;

	private TextView bj;
	private TextView cd;
	private TextView gz;
	private TextView cq;
	private TextView sz;
	private TextView tj;
	// private TextView gpscity;
	private ImageView close_icon;
	private TextView gpsTv;
	// private TextView gpsRemind;
	EditText edit_inputcity;
	private CityNoDBManager cityNoDBManager;
	private SQLiteDatabase database2;
	private FlowLayout area_container;
	private ArrayList<CityModel> arrayLitArea;// 区域列表
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			afterCitySelected(arg2.getStringExtra("city"));
		}
	}

	public static void goToCityListActivity(Context context) {
		Intent intent = new Intent(context, CityListActivity.class);
		context.startActivity(intent);
	}

	/**
	 * 从数据库获取城市数据
	 * 
	 * @return
	 */
	private ArrayList<CityModel> getCityNames() {
		ArrayList<CityModel> names = new ArrayList<CityModel>();
		Cursor cursor = database.rawQuery(
				"SELECT * FROM T_City ORDER BY NameSort", null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			CityModel cityModel = new CityModel();
			cityModel.setCityName(cursor.getString(cursor
					.getColumnIndex("CityName")));
			cityModel.setNameSort(cursor.getString(cursor
					.getColumnIndex("NameSort")));
			names.add(cityModel);
		}
		return names;
	}

	/**
	 * 城市列表点击事件
	 * 
	 * @author sy
	 * 
	 */
	class CityListOnItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {
			if (pos == 0) {
				return;
			}
			CityModel cityModel = (CityModel) city_list.getAdapter().getItem(
					pos);
			String city = cityModel.getCityName();
			afterCitySelected(city);
			// city_list.smoothScrollToPosition(0);
			city_list.setSelection(0);// 设置选择项为第一项
		}

	}

	private void afterCitySelected(String city) {
		String cityCode = "";
		SPUtils.put(this, null, SPContants.SELECT_CITY, city);
		gpsTv.setText("重新定位");
		// Intent intent = new Intent();
		// intent.putExtra("choose", city);
		// setResult(102,intent);
		if (city.equals("重庆市") || city.equals("北京市") || city.equals("天津市")// 特殊直辖市
				|| city.equals("上海市")) {
			cityCode = cityNoDBManager.queryPriovinceNo(city);
			cityCode = cityCode.substring(0, cityCode.length() - 4);
		} else {
			cityCode = cityNoDBManager.queryCityNo(city);
		}
		arrayLitArea = cityNoDBManager.queryArea(cityCode);

		addArea(arrayLitArea);
		// finish();
	}

	@SuppressLint("NewApi") private void addArea(ArrayList<CityModel> array) {
		area_container.removeAllViews();
		for (int i = 0; i < array.size(); i++) {
			CityModel array_element = array.get(i);
			TextView textView = new TextView(this);
			textView.setText(array_element.getAreaName());
			textView.setTag(array_element.getAreaCode());
			textView.setTextSize(15);
			textView.setPadding(10, 10, 10, 10);
			textView.setBackground(getResources().getDrawable(
					R.drawable.btn_choose_city));
			android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutParams.setMargins(5, 5, 5, 5);
			area_container.addView(textView,
					area_container.getChildCount() - 1, layoutParams);
			textView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					SPUtils.put(CityListActivity.this, null,
							SPContants.SELECT_AREA, "");
				}
			});
			Log.v("area",
					array_element.getAreaCode() + ":"
							+ array_element.getAreaName());
		}
	}

	/**
	 * 为ListView设置适配器
	 * 
	 * @param list
	 */
	private void setAdapter(List<CityModel> list) {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View headview = layoutInflater.inflate(R.layout.inculd_city_headview,
				null);
		area_container = (FlowLayout) headview
				.findViewById(R.id.area_container);
		String gpsCity = SPUtils.get(this, null, SPContants.SELECT_CITY, "")
				+ "";
		if (gpsCity.equals("")) {
			// gpsTv.setText("杭州");
			gpsTv.setText("定位失败请重新定位");
		} else {
			gpsTv.setText(gpsCity);
		}
		// bj = (TextView) headview.findViewById(R.id.bj);
		// cd = (TextView) headview.findViewById(R.id.cd);
		// gz = (TextView) headview.findViewById(R.id.gz);
		// sz = (TextView) headview.findViewById(R.id.sz);
		// tj = (TextView) headview.findViewById(R.id.tj);
		// cq = (TextView) headview.findViewById(R.id.cq);
		// setClickLis(bj, "北京");
		// setClickLis(cd, "成都");
		// setClickLis(gz, "广州");
		// setClickLis(sz, "深圳");
		// setClickLis(tj, "天津");
		// setClickLis(cq, "重庆");
		city_list.addHeaderView(headview);
		if (list != null) {
			adapter = new ListAdapter(this, list);
			city_list.setAdapter(adapter);
		}

	}

	private void setClickLis(TextView tv, final String name) {
		tv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				afterCitySelected(name);
			}
		});
	}

	/**
	 * ListViewAdapter
	 * 
	 * @author sy
	 * 
	 */
	private class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<CityModel> list;

		public ListAdapter(Context context, List<CityModel> list) {

			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {
				// 当前汉语拼音首字母
				// getAlpha(list.get(i));
				String currentStr = list.get(i).getNameSort();
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? list.get(i - 1)
						.getNameSort() : " ";
				if (!previewStr.equals(currentStr)) {
					String name = list.get(i).getNameSort();
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(list.get(position).getCityName());
			String currentStr = list.get(position).getNameSort();
			String previewStr = (position - 1) >= 0 ? list.get(position - 1)
					.getNameSort() : " ";
			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}
			return convertView;
		}

		private class ViewHolder {
			TextView alpha;
			TextView name;
		}

	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s) + 1;
				city_list.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.GONE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 1500);
			}
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.gpsTv:
			// LocManager.getInstance().startLocOnce(this);
			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		return R.layout.city_list;
	}

	@Override
	protected void onInitController() {
		
	}

	@SuppressLint("ResourceAsColor") @Override
	protected void onInit() {
		// TODO Auto-generated method stub
		setStatusBarColor(R.color.home_blue);
		close_icon.setOnClickListener(this);
		gpsTv = (TextView) findViewById(R.id.gpsTv);
		// gpsRemind= (TextView) findViewById(R.id.gpsTv);
		gpsTv.setText(SPUtils.get(this, null, SPContants.SELECT_CITY, "") + "");
		gpsTv.setOnClickListener(this);
		cityNoDBManager = new CityNoDBManager(this);
		DBManager dbManager = new DBManager(this);
		dbManager.openDateBase();
		cityNoDBManager.openDateBase();
		database2 = SQLiteDatabase
				.openOrCreateDatabase(CityNoDBManager.DB_PATH2 + "/"
						+ CityNoDBManager.DB_NAME2, null);
		edit_inputcity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CityListActivity.this,
						ChooseCityActivity.class);
				startActivityForResult(intent, 101);
			}
		});
		// dbManager.closeDatabase();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		mCityNames = getCityNames();
		database.close();
		cityLetterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();

		initOverlay();
		setAdapter(mCityNames);
		city_list.setOnItemClickListener(new CityListOnItemClick());
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub
		
	}

	

	// @Override
	// public void onLoctionStart() {
	//
	// }

	// @Override
	// public void onLocationSuccess(double lat, double lng, String city,
	// String addr) {
	// // TODO Auto-generated method stub
	// Utils.setMyCity(city);
	// Utils.setMyLatLng(lat + "", lng + "");
	// gpscity.setText(Utils.getMyCity());
	// gpsRemind.setText("定位成功");
	// Utils.notifyAllLocChanged();
	// }
}